﻿var curDefType= {type:"p2p","groupId":"",targetId:""};
$(document).ready(function() {  
    var uuid = guid(); // uuid在一个会话唯一  
    var nameOnline = ''; // 上线姓名    
    var onlineName = new Map(); // 已上线人员, <requestId, name>  
    var online= false; //是否上线
    $("#name").attr("disabled","disabled");  
    $("#onlineBtn").attr("disabled","disabled");  
    //$("#banana").hide();  
  
    // 初始化websocket  
    var socket;  
    if (!window.WebSocket) {  
        window.WebSocket = window.MozWebSocket;  
    }  
    if (window.WebSocket) {  
        socket = new WebSocket("ws://localhost:8080/");  
        socket.onmessage = function(event) {  
            console.log("收到服务器消息:" + event.data);
			var request = JSON.parse(event.data);
			if(!request.isSucc){
				var dialog= new Dialog();
				dialog.alert(request.message);
				return;
			}
			if (request.serviceId == 1001 && request.requestId==uuid) { //上线  
				$("#onlineBtn").val("下线")
				if (request.isSucc) {  
				   // 上线成功，初始化已上线人员  
					onlineName.clear();  
					$("#onlineBtn").addClass("online");
					$("#friends").empty();  
					for (var reqId in request.hadOnline) {  
						onlineName.put(reqId, request.hadOnline[reqId]);  
					}  
					initOnline();                                
					$("#name").attr("disabled","disabled");
					online= true;
				} else {  
					 alert("上线失败");  
				}  
			} else if (request.serviceId == 1004 & request.requestId==uuid) {//下线  
				$("#onlineBtn").val("上线");
				if (request.isSucc) {  
					onlineName.clear();
					$("#onlineBtn").removeClass("online");					
					$("#friends").empty();  
					$("#name").removeAttr("disabled");  
					$("#onlineBtn").removeAttr("disabled");
				} else {  
					alert("下线失败");   
				}
			}  
			else if (request.serviceId == 1001 || request.serviceId == 1004) { // 有人上线/下线  
				if (request.serviceId == 1001) {  
					onlineName.put(request.requestId, request.name);  
				}  
				if (request.serviceId == 1004) {  
					onlineName.remove(request.requestId);  
				}
				initOnline();  
			} else if (request.serviceId == 1002) { // 有人发消息  
				appendApple(request.targetId,request.requestId,request.name, request.message);  
			} else if(request.serviceId == 1005 || request.serviceId == 1006) { //新建群信息 or 加入新群
				appendGroup(request.hadOnline);
			}
        };  
        socket.onopen = function(event) {  
            $("#name").removeAttr("disabled");  
            $("#onlineBtn").removeAttr("disabled");  
             console.log("已连接服务器");  
        };  
        socket.onclose = function(event) { // WebSocket 关闭  
            onsole.log("WebSocket已经关闭!");  
        };  
        socket.onerror = function(event) {  
            console.log("WebSocket异常!");  
        };  
    } else {  
        alert("抱歉，您的浏览器不支持WebSocket协议!"); 
    }  
      
  // WebSocket发送请求  
    function send(message) {  
        if (!window.WebSocket) { return; }  
        if (socket.readyState == WebSocket.OPEN) {  
            socket.send(message);  
        } else {  
             console.log("WebSocket连接没有建立成功!");  
            alert("您还未连接上服务器，请刷新页面重试。");   
        }  
    }  
	
      // 刷新上线人员  
    function initOnline() {  
        $("#friends").empty(); 
		var content= "<ul style='padding:0px;margin: 4px 4px;list-style-type:none;'>";
        for (var i=0;i<onlineName.size();i++) {
			var key= onlineName.element(i).key;
			if(key!=uuid){
				content+=("<li reqId='"+key+"' onclick='personTalk()'>" + onlineName.element(i).value + "</li>");  
			}
        }
		content+="</ul>"
		$("#friends").append(content);  
		displayFriends();
		initFriendsEvent();
    }  
     // 追加聊天信息  
    function appendApple(target,req,name, message) {
		console.log(uuid);
		name= name.substr(0,1);
		if(target==req){
			$("#talkContent_"+target).append('<tr><td style="width:600px;"><div class="msgR"><div class="msgTitleR">' + name + '</div><div class="msgCententR">' + message + '</div></div></td></tr>');
		}else{
			if(uuid==req){
				$("#talkContent_"+target).append('<tr><td style="width:600px"><div class="msgR"><div class="msgTitleR">' + name + '</div><div class="msgCententR">' + message + '</div></div></td></tr>');
			}else {
				$("#talkContent_"+req).append('<tr><td style="width:600px"><div class="msg"><div class="msgTitle">' + name + '</div><div class="msgCentent">' + message + '</div></div></td></tr>');
			}

		}
    }  
	
	function appendGroup(group){
		var groupName= group.groupName+"（"+group.groupId+"）";
		$("#groupList").append('<li group="'+group.groupId+'" onclick="groupTalk()">'+groupName+'</li>');
		initGroupEvent();
	}
	
    $("#onlineBtn").bind("click", function() {
	    var value= $("#onlineBtn").val();
		var name = $("#name").val();  
		if (name == null || name == '') {  
			 alert("请输入您的尊姓大名。");  
			return;  
		}
		if(value=="上线"){
			nameOnline = name;  
			 // 上线  
			send(JSON.stringify({"requestId":uuid, "serviceId":1001, "name":name}));  
		}else{
		   send(JSON.stringify({"requestId":uuid, "serviceId":1004}));  
		}
       
    });  

    $("#sendBtn").bind("click", function() {  
        var message = $("#messageInput").val();  
        if (message == null || message.trim() == '') {  
            return;  
        }
		if(!online){
			alert("请先上线哟。");
			return;
		}
		var message= $.extend(curDefType,{"requestId":uuid, "serviceId":1003, "name":nameOnline, "message":HTMLDecode(message)});
        // 发送聊天消息  
        send(JSON.stringify(message));  
        $("#messageInput").val("");  
    });  
 
	$("#messageInput").keyup(function(e){
	    if(event.keyCode==13){
			$("#sendBtn").click();
		}
	});
	
	//新建群
	$("#newGroup").bind("click",function(){
		var dialog= null;
		if(!online){
			dialog= new Dialog();
			dialog.alert("请先上线。");
			return;
		}
		var styleConfig={width:400,height:300};
		var dialog= new Dialog();
		dialog.openDialog("<div style='float:left;margin:5px;width:100%'>群名称：</div><div style='float:left;margin:5px 5px;width:100%'><input type='text' id='groupName'/></div>");
		dialog.confirm(function($dialog){
			var groupName= $dialog.find("#groupName").val();
			console.log("new group: "+groupName+" uid:"+uuid);
			send(JSON.stringify({"requestId":uuid, "serviceId":1005,"message":groupName}));
		});
	});
	//加入群
	$("#joinGroup").bind("click",function(){
		var dialog= null;
		if(!online){
			dialog= new Dialog();
			dialog.alert("请先上线。");
			return;
		}
		var styleConfig={width:400,height:300};
		var dialog= new Dialog();
		dialog.openDialog("<div style='float:left;margin:5px;width:100%'>群号：</div><div style='float:left;margin:5px 5px;width:100%'><input type='text' id='groupId'/></div>");
		dialog.confirm(function($dialog){
			var groupId= $dialog.find("#groupId").val();
			console.log("new group: "+groupId+" uid:"+uuid);
			send(JSON.stringify({"requestId":uuid, "serviceId":1006,"targetId":groupId}));
		});
	});
	
	function initFriendsEvent(){
		$("#friends").find("li").each(function(){
			var $li= $(this);
			$li.unbind("mouseover").bind("mouseover",function(){
				$li.addClass("limouseover");
			});
			$li.unbind("mouseleave").bind("mouseleave",function(){
				$li.removeClass("limouseover");
			});
		});
		
	}
	
	function initGroupEvent(){
		$("#groupList").find("li").each(function(){
			var $li= $(this);
			$li.unbind("mouseover").bind("mouseover",function(){
				$li.addClass("limouseover");
			});
			$li.unbind("mouseleave").bind("mouseleave",function(){
				$li.removeClass("limouseover");
			});
		});
	}
	
}); 

function groupTalk(){
	var $group= $(event.target);
	curDefType.type= "p2b";
	curDefType.targetId= $group.attr("group");
	var title= $group.text();
	$("#windowTitle").html("<div style='width: 600px;text-overflow: ellipsis;overflow: hidden;'><div class='circle'>"+title.substr(0,1)+"</div><div class='title'>"+title+"</div></div>");
	var id= curDefType.targetId;
	$("#groupList").children().each(function(){
		var $group= $(this);
		if(id!=$group.attr("group")){
			$group.removeClass("selected");
		}else{
			$group.addClass("selected");
		}
	});
	var hasExist= false
	$("#windowTalk").children().each(function(){
		var $cur= $(this);
		if($cur.attr("id")==id){
			hasExist=true;
			$cur.addClass("winTitleSelected");
		}else{
			$cur.removeClass("winTitleSelected");
		}
	});
	if(!hasExist){
		$("#windowTalk").append("<div class='windowTitle winTitleSelected' id='"+id+"' type='p2b' title='"+$group.text()+"' onclick='windowSelected()'>"+$group.text()+"</div>");
		$("#talkContent").children().each(function(){
			var $this= $(this);
			$this.css("display","none");
		});
		$("#talkContent").append("<table id='talkContent_"+id+"' border='0' style='max-width: 720px;'></table>");
		initWindowTalkEvent();
	}else{
		$("#talkContent").children().each(function(){
			var $this= $(this);
			if($this.attr("id")=="talkContent_"+id){
				$this.css("display","block");
			}else{
				$this.css("display","none");
			}
		});
	}
	var len= $("#windowTalk").children().length;
	var height= parseInt($("#windowTalk").height()/len)-2;
	if(height>40){
		return;
	}
	$("#windowTalk").children().each(function(){
		var $this= $(this);
		$this.css("height",height);
		$this.css("line-height",height+"px");
	});
}

function personTalk(){
	var $person= $(event.target);
	curDefType.type= "p2p";
	curDefType.targetId= $person.attr("reqId");
	var title= $person.text();
	$("#windowTitle").html("<div style='width: 600px;text-overflow: ellipsis;overflow: hidden;'><div class='circle'>"+title.substr(0,1)+"</div><div class='title'>"+title+"</div></div>");
	$person.addClass("selected");
	$("#friends").find("li").each(function(){
		var $cur= $(this);
		var reqId= $cur.attr("reqId");
		if(reqId!=curDefType.targetId && $cur.hasClass("selected")){
			$cur.removeClass("selected");
			return false;
		}
	});
	var id=curDefType.targetId;
	var hasExist= false;
	$("#windowTalk").children().each(function(){
		var $this= $(this);
		if($this.attr("id")==id){
			$this.addClass("winTitleSelected");
			hasExist= true;
		}else{
			$this.removeClass("winTitleSelected");
		}
	});
	if(hasExist){
		$("#talkContent").children().each(function(){
			var $this= $(this);
			if($this.attr("id")=="talkContent_"+id){
				$this.css("display","block");
			}else{
				$this.css("display","none");
			}
		});
	}
	if(!hasExist){
		$("#windowTalk").append("<div class='windowTitle winTitleSelected' id='"+id+"' type='p2p' title='"+$person.text()+"'  onclick='windowSelected()'>"+$person.text()+"</div>");
		$("#talkContent").children().each(function(){
			var $this= $(this);
			$this.css("display","none");
		});
		$("#talkContent").append("<table id='talkContent_"+id+"' border='0' style='max-width: 720px;'></table>");
		initWindowTalkEvent();
	}
	var len= $("#windowTalk").children().length;
	var height= parseInt($("#windowTalk").height()/len)-2;
	if(height>40){
		return;
	}
	$("#windowTalk").children().each(function(){
		var $this= $(this);
		$this.css("height",height);
		$this.css("line-height",height+"px");
	});
}

function initWindowTalkEvent(){
	$("#windowTalk").children().each(function(){
		var $this= $(this);
		$this.unbind("mouseover").bind("mouseover",function(){
			$this.addClass("windowTalkmover");
		});
		$this.unbind("mouseleave").bind("mouseleave",function(){
			$this.removeClass("windowTalkmover");
		});
	});
}

function windowSelected(){
	var $window= $(event.target);
	$("#windowTalk").children().each(function(){
		$(this).removeClass("winTitleSelected");
	});
	$window.addClass("winTitleSelected");
	var title= $window.attr("title");
	$("#windowTitle").html("<div style='width: 600px;text-overflow: ellipsis;overflow: hidden;'><div class='circle'>"+title.substr(0,1)+"</div><div class='title'>"+title+"</div></div>");
	var id= $window.attr("id");
	//初始化当前窗口消息类型和目标对象
	curDefType.type= $window.attr("type");
	curDefType.targetId= id;
	$("#talkContent").children().each(function(){
		var $this= $(this);
		if($this.attr("id")=="talkContent_"+id){
			$this.css("display","block");
		}else{
			$this.css("display","none");
		}
	});
	/*$("#friends").find("li").each(function(){
		var $cur= $(this);
		var reqId= $cur.attr("reqId");
		if(reqId!=id){
			$cur.removeClass("selected");
		}else{
			$cur.addClass("selected");
		}
	});*/
}      

function guid() {  
    function S4() {  
       return (((1+Math.random())*0x10000)|0).toString(16).substring(1);  
    }  
    return (S4()+S4()+"-"+S4()+"-"+S4()+"-"+S4()+"-"+S4()+S4()+S4());  
}  

function HTMLDecode(text) { 
    var temp = document.createElement("div"); 
    temp.innerHTML = text; 
    var output = temp.innerText || temp.textContent; 
    temp = null; 
    return output; 
} 

function fgSwitch(type){
	if(type=="friends"){
		displayFriends();
	}else if(type=="groups"){
		displayGroups();
	}
}

function displayFriends(){
	$("#friends").css('display','block'); 
	$("#groups").css('display','none'); 
	$("#fgSwitch a").first().addClass("selected");
	$("#fgSwitch a").last().removeClass("selected");
}

function displayGroups(){
	$("#friends").css('display','none'); 
	$("#groups").css('display','block'); 
	$("#fgSwitch a").first().removeClass("selected");
	$("#fgSwitch a").last().addClass("selected");
}


